<?php

namespace lxs\wechat;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class OpenInterface
{

    private mixed $secret;
    private mixed $appId;

    public function __construct()
    {
        $this->appId = env('WECHAT_APP_ID');
        $this->secret = env('WECHAT_APP_SECRET');
    }

    /**
     * 获取微信用户openid/unionid
     */
    public function getOpenId($code): array
    {
        $url = "https://api.weixin.qq.com/sns/jscode2session";
        $response = Http::get($url, [
            'appid' => $this->appId,
            'secret' => $this->secret,
            'js_code' => $code,
            'grant_type' => 'authorization_code'
        ]);
        if ($response->successful()) {
            $data = $response->json();
            return [
                'openid' => $data['openid'] ?? '',
                'session_key' => $data['session_key'] ?? '',
                'unionid' => $data['unionid'] ?? ''
            ];
        }
        return [
            'openid' => '',
            'session_key' => '',
            'unionid' => ''
        ];
    }


    /**
     * 获取access_token
     */
    protected function getAccessToken($appid='', $secret=''): ?string
    {
        if ($appid != '' && $secret != '') {
            $this->appId = $appid;
            $this->secret = $secret;
        }
        $apiUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->secret";
        $response = Http::get($apiUrl);
        if ($response->successful()) {
            $data = $response->json();
            if (isset($data['access_token'])) {
                if ( $appid == '' && $secret == '') {
                    Cache::put('access_token', $data['access_token'], $data['expires_in'] - 60);
                }
                return $data['access_token'];
            } else {
                Log::error(date('Y-m-d H:i:s') . '获取access_token失败' . PHP_EOL . $response->body());
                return null;
            }
        } else {
            return null;
        }
    }

}
